package com.atguigu.tingshu.common.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import java.util.Enumeration;


/***
 * feign拦截器 全局feign调用生效
 */
@Component
public class FeignInterceptor implements RequestInterceptor {

    /**
     * feign调用前触发
     *
     * @param requestTemplate
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获取Request对象
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 非空 有request才处理
        if (requestAttributes != null) {
            // 获取原request
            HttpServletRequest request = requestAttributes.getRequest();
            // 获取原request中的数据
            Enumeration<String> headerNames = request.getHeaderNames();
            // 遍历获取
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String value = request.getHeader(name);
                // 将原request中的参数存储到Feign request中
                requestTemplate.header(name, value);
            }
        }
    }
}